package com.cloud.bc.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import com.cloud.bc.mapper.BcFinancesMapper;
import com.cloud.bc.mapper.BcUserBankcardsMapper;
import com.cloud.bc.model.entity.BcFinanceRecords;
import com.cloud.bc.model.entity.BcFinances;
import com.cloud.bc.model.entity.BcUserBankcards;
import com.cloud.bc.model.entity.BcWithdrawalOrders;
import com.cloud.bc.mapper.BcWithdrawalOrdersMapper;
import com.cloud.bc.service.BcConfigsService;
import com.cloud.bc.service.BcFinanceRecordsService;
import com.cloud.bc.service.BcUserBankcardsService;
import com.cloud.bc.service.BcWithdrawalOrdersService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.bc.util.OrderNoUtil;
import com.cloud.common.model.enums.CurrencyTypeEnum;
import com.cloud.common.model.enums.WithdrawalBindTypeEnum;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

/**
 * 提现订单
 *
 * @author douhaichao code generator
 * @date 2021-01-19 21:19:38
 */
@Service
@AllArgsConstructor
public class BcWithdrawalOrdersServiceImpl extends ServiceImpl<BcWithdrawalOrdersMapper, BcWithdrawalOrders> implements BcWithdrawalOrdersService {
    private final BcFinanceRecordsService bcFinanceRecordsService;
    private final BcFinancesMapper bcFinancesMapper;
    private final BcConfigsService bcConfigsService;
    private final BcUserBankcardsMapper bcUserBankcardsMapper;
    private final OrderNoUtil orderNoUtil;

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public BcWithdrawalOrders selectOne(BcWithdrawalOrders req) {
        QueryWrapper queryWrapper = new QueryWrapper<BcWithdrawalOrders>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<BcWithdrawalOrders> selectAll(BcWithdrawalOrders req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<BcWithdrawalOrders> selectPage(Page page, BcWithdrawalOrders req) {
        QueryWrapper<BcWithdrawalOrders> bcWithdrawalOrdersQueryWrapper = new QueryWrapper<>();
        bcWithdrawalOrdersQueryWrapper.setEntity(req);
        bcWithdrawalOrdersQueryWrapper.orderByDesc("id");
        IPage<BcWithdrawalOrders> list = baseMapper.selectPage(
                page,bcWithdrawalOrdersQueryWrapper);
        return list;
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(BcWithdrawalOrders req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

    @Transactional
    @Override
    public Integer apply(BcWithdrawalOrders req) {
        //默认是微信提现方式
        req.setWay(StrUtil.isEmpty(req.getWay()) ? WithdrawalBindTypeEnum.WEIXINPAY.getName() : req.getWay());

        //判断是否绑卡
        QueryWrapper<BcUserBankcards> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(BcUserBankcards::getUserId, req.getUserId());
        queryWrapper.lambda().eq(BcUserBankcards::getWay, req.getWay());
        BcUserBankcards bcUserBankcardsResult = bcUserBankcardsMapper.selectOne(queryWrapper);
        if (null == bcUserBankcardsResult) {
            return -3;
        }

        //验证最大，最小提现额度
        Integer maxWithdrawals = Convert.toInt(bcConfigsService.getValue("maxWithdrawals"), 1000);
        Integer minWithdrawals = Convert.toInt(bcConfigsService.getValue("minWithdrawals"), 0);
        if (Convert.toInt(req.getCash(), 0) < minWithdrawals ||
                Convert.toInt(req.getCash(), 0) > maxWithdrawals) {
            //提现额度错误，提现失败
            return -2;
        }
//1、提现扣减
        BigDecimal cash = Convert.toBigDecimal(req.getCash());

        BcFinances bcFinances = new BcFinances();
        bcFinances.setUserId(req.getUserId());
        bcFinances.setMoney(cash);
        boolean result = bcFinancesMapper.sub(bcFinances);
        if (!result) {
            //余额不够
            return -1;
        }
//2、记录流水

        BcFinanceRecords bcFinanceRecords = new BcFinanceRecords();
        bcFinanceRecords.setUserId(bcFinances.getUserId());
        bcFinanceRecords.setCurrencyType(CurrencyTypeEnum.CASH.getCode());
        bcFinanceRecords.setType(0);
        bcFinanceRecords.setPid(0);
        bcFinanceRecords.setIncome(NumberUtil.mul(cash, -1));
        bcFinanceRecords.setRemark("申请提现:" + cash + "元");
        bcFinanceRecordsService.recodeAdd(bcFinanceRecords);
//3、新增提现表
        //计算手续费,默认收30%手续费
        String serviceWithdrawals = Convert.toStr(bcConfigsService.getValue("serviceWithdrawals"), "30");
        serviceWithdrawals = serviceWithdrawals.replace("%", "");
        //实付金额=100%-扣减手续费
        BigDecimal withService = NumberUtil.sub(100, Convert.toBigDecimal(serviceWithdrawals));
        //总金额除100
        withService = NumberUtil.div(withService, 100);
        //实付金额
        BigDecimal actualCash = NumberUtil.mul(withService, cash);
        req.setActualCash(actualCash);

        req.setAccountData("");
        //查询账号和姓名
        req.setAccountName(bcUserBankcardsResult.getName());
        req.setAccountNumber(bcUserBankcardsResult.getNumber());
        req.setOrderId(orderNoUtil.getWithdrawalOrderNo());
        baseMapper.insert(req);
        return 1;
    }
}
